import { Button, Checkbox, Form, FormProps, Input, MessagePlugin } from 'tdesign-react'
import FormItem from 'tdesign-react/es/form/FormItem'
import { Link } from 'react-router'
import { reqAuthLogin } from '../api/auth.ts'
import { useEffect } from 'react'

export default function PhoneLogin() {
  const [form] = Form.useForm()

  useEffect(() => {
    form.setFields([{ name: 'mobile', value: 15154031238 }, { name: 'password', value: 'admin123' }, { name: 'agree', value: true }])
  }, [])

  const onSubmit: FormProps['onSubmit'] = async (e) => {
    if (e.validateResult === true) {
      try {
        const res = await reqAuthLogin({ ...e.fields })
        if (res) {
          localStorage.setItem('token', res.accessToken)
          localStorage.setItem('refreshToken', res.refreshToken)
          MessagePlugin.success('登陆成功')
          window.ipcRenderer.invoke('open-main')
        }
      } catch (error) {
      }

    }
  }

  return (
    <div className="flex flex-col items-center justify-center">
      <h1 className="font-bold text-xl mb-8">登录</h1>

      <Form className="w-[320px]" form={form} onSubmit={onSubmit} resetType="empty" preventSubmitDefault showErrorMessage>
        <FormItem name="mobile" rules={[{ required: true, message: '请输入手机号', type: 'error' }, { telnumber: true, message: '请输入正确的手机号码' }]}>
          <Input placeholder="请输入手机号" size="large"/>
        </FormItem>
        <FormItem name="password" rules={[{ required: true, message: '请输入密码', type: 'error' }, { min: 6 }]}>
          <Input placeholder="请输入密码" size="large"/>
        </FormItem>
        <FormItem name="agree" rules={[{ validator: v => !!v, message: '请同意协议', type: 'error' }]}>
          <Checkbox>
            <div className="flex-row items-center text-sm w-full text-center text-gray-700">我已阅读并同意
              <a className="text-blue-500" href="#">《服务条款》</a>
              <a className="text-blue-500" href="#">《隐私政策》</a>
            </div>
          </Checkbox>
        </FormItem>
        <FormItem>
          <Button className="bg-linear-to-r from-[#3588FF] to-[#8D76FF]" style={{ border: 'none' }} size="large" type="submit" block>登录</Button>
        </FormItem>
      </Form>

      <div className="flex justify-between flex-row w-[320px] text-sm text-[#177BFF] mt-5">
        <Link to="/">扫码登陆</Link>
        <Link to="/reset">忘记密码</Link>
      </div>
    </div>
  )
}
